from azure.keyvault.secrets import SecretClient
from azure.identity import DefaultAzureCredential
import os

class CredentialManager:
    def __init__(self, keyvault_url: str = None):
        self.keyvault_url = keyvault_url or os.getenv("AZ_KEYVAULT_URL")
        self.credential = DefaultAzureCredential()
        self.client = SecretClient(
            vault_url=self.keyvault_url,
            credential=self.credential
        )
        
    def get_client_secret(self) -> str:
        """安全获取客户端密钥"""
        return self.client.get_secret("exchange-client-secret").value
    
    def store_backup_key(self, key_name: str, key_value: str):
        """存储备份加密密钥"""
        self.client.set_secret(key_name, key_value)
    
    def rotate_credentials(self):
        """凭证轮换操作"""
        new_secret = self.client.rotate_secret("exchange-client-secret")
        return new_secret.id